<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search parkingCostSearch" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="小区名称" prop="projectId">
            <el-select v-model="queryParams.projectId" class="m-2" placeholder="请选择小区名称" clearable style="width: 240px" @change="handleQuery">
              <el-option v-for="item in xmOptions" :key="item.id" :label="item.projectName" :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="小区名称">
            <el-select
              class="slese"
              @visible-change="xmhandleVisibleChange"
              v-model="queryParams.projectId"
              placeholder="请选择项目"
              ref="selectRef"
              @change="handleQuery"
            >
              <el-option class="CWDropdown" v-for="item in xmOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
            </el-select>
          </el-form-item> -->
          <el-form-item label="车位号" prop="garageNumber">
            <el-input v-model="queryParams.garageNumber" placeholder="请输入车位号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="车牌号" prop="garageCarNumber">
            <el-input v-model="queryParams.garageCarNumber" placeholder="请输入车牌号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="车位物业费周期开始时间" prop="garageManagementStartDate">
            <el-date-picker
              clearable
              v-model="queryParams.garageManagementStartDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择车位物业费周期开始时间"
            />
          </el-form-item>
          <el-form-item label="车位物业费周期停止时间" prop="garageManagementEndDate">
            <el-date-picker
              clearable
              v-model="queryParams.garageManagementEndDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择车位物业费周期停止时间"
            />
          </el-form-item>
          <el-form-item label="车位收车时间" prop="garageCollectionDate">
            <el-date-picker
              clearable
              v-model="queryParams.garageCollectionDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择车位收车时间"
            />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:cost:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:cost:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:cost:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:cost:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="costList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="小区名称" align="center" prop="projectName" />
        <el-table-column label="房屋号" align="center" prop="houseNumber" />
        <el-table-column label="车位号" align="center" prop="garageNumber" />
        <!-- <el-table-column label="车位面积" align="center" prop="garageArea" /> -->
        <el-table-column label="车位管理费" align="center" prop="garageManagementCost" />
        <el-table-column label="车牌号" align="center" prop="garageCarNumber" />
        <el-table-column label="是否开具发票" align="center" prop="houseWasteCose">
          <template #default="scope">
            <dict-tag :options="is_need_invoice" :value="scope.row.isNeedInvoice" />
          </template>
        </el-table-column>
        <el-table-column label="车位管理费周期" align="center" prop="garageManagementStartDate" width="300">
          <template #default="scope">
            <span>{{ parseTime(scope.row.garageManagementStartDate, '{y}-{m}-{d}') }}</span>
            <span style="margin:0 10px;">至</span>
            <span>{{ parseTime(scope.row.garageManagementEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="车位收车时间" align="center" prop="garageCollectionDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.garageCollectionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:cost:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:cost:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Cost" lang="ts">
import { listCost, delCost, } from '@/api/business/parkingLotCost';
// import { listGarageInfo } from '@/api/business/garageInfo';
// import { listHouseInfo } from '@/api/business/houseInfo';
// import { HouseCostVO } from '@/api/business/houseCost/types';
// import { GarageInfoVO } from '@/api/business/garageInfo/types';
import { CostVO, CostQuery, CostForm } from '@/api/business/parkingLotCost/types';
import { listStandard } from '@/api/business/standard';
import { listProject } from '@/api/business/project';
import { ref } from 'vue'
// import { addDays } from 'date-fns';
import { formatDate } from '@/utils/index.ts'
// let editFlag = ref(false)
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { charge_category } = toRefs<any>(proxy?.useDict('charge_category'));
const { is_need_invoice } = toRefs<any>(proxy?.useDict('is_need_invoice'));
const router = useRouter();

const costList = ref<CostVO[]>([]);
// const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
// const costFormRef = ref<ElFormInstance>();

// const dialog = reactive<DialogOption>({
//   visible: false,
//   title: ''
// });

const initFormData: CostForm = {
  garageCostId: undefined,
  projectId: undefined,
  houseId: undefined,
  houseNumber: undefined,
  garageNumber: undefined,
  garageArea: undefined,
  garageCategory: undefined,
  garageManagementCost: undefined,
  garageCarNumber: undefined,
  garageManagementStartDate: undefined,
  garageManagementEndDate: undefined,
  isNeedInvoice: undefined,
  remark: undefined,
}
const data = reactive<PageData<CostForm, CostQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: undefined,
    houseId: undefined,
    houseNumber: undefined,
    garageNumber: undefined,
    garageArea: undefined,
    garageCategory: undefined,
    garageManagementCost: undefined,
    garageCarNumber: undefined,
    garageManagementStartDate: undefined,
    garageManagementEndDate: undefined,
    isNeedInvoice: undefined,
    params: {
      }
  },
  rules: {
    garageCostId: [
      { required: true, message: "车位管理费缴费记录id不能为空", trigger: "blur" }
    ],
    projectId: [
      { required: true, message: "小区id不能为空", trigger: "blur" }
    ],
    houseId: [
      { required: true, message: "房屋号不能为空", trigger: "blur" }
    ],
    garageNumber: [
      { required: true, message: "车位号不能为空", trigger: "blur" }
    ],
    garageManagementCost: [
      { required: true, message: "车位管理费不能为空", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (!value&&value!=0) {
            return callback(new Error('车位管理费不能为空'));
          }
          if (value <= 0) {
            return callback(new Error('车位管理费必须大于零'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    garageCarNumber: [
      { required: true, message: "车牌号不能为空", trigger: "blur" }
    ],
    garageManagementStartDate: [
      { required: true, message: "车位管理费周期开始时间不能为空", trigger: "blur" }
    ],
    garageManagementEndDate: [
      { required: true, message: "车位管理费周期停止时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const XQtotal = ref(0)

/** 查询车位管理费缴费记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCost(queryParams.value);
  costList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
// const cancel = () => {
//   reset();
//   dialog.visible = false;
//   editFlag.value = false
// }

/** 表单重置 */
// const reset = () => {
//   form.value = {...initFormData};
//   costFormRef.value?.resetFields();
// }

/** 搜索按钮操作 */
const handleQuery = () => {
  sessionStorage.removeItem("queryCKParams")
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  sessionStorage.removeItem("queryCKParams")
  queryFormRef.value?.resetFields();
  queryParams.value.projectId=undefined
  // queryParams.value.garageCategory=undefined
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: CostVO[]) => {
  ids.value = selection.map(item => item.garageCostId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: '/costManagement/parkingLotCostAdd', query: { type:'add' } })
  /* reset();
  queryParamsFW.value.pageNum = 1
  dialog.visible = true;
  dialog.title = "添加车位管理费缴费记录";
  editFlag.value = false */
}

/** 修改按钮操作 */
const handleUpdate = async (row?: CostVO) => {
  sessionStorage.setItem("queryCKParams", JSON.stringify(queryParams.value));
  router.push({ path: '/costManagement/parkingLotCostAdd',query: { type:'edit',garageCostId: row?.garageCostId} })
  /* editFlag.value = true
  reset();
  const _garageCostId = row?.garageCostId || ids.value[0]
  const res = await getCost(_garageCostId);
  Object.assign(form.value, res.data);
  queryParamsFW.value.pageNum = 1
  dialog.visible = true;
  dialog.title = "修改车位管理费缴费记录";
  // addCheckProjectId('edit')
  console.log(form.value)
  getHouseList('edit') */
}

/** 提交按钮 */
// const submitForm = () => {
//   form.value.garageManagementCost =  CWGLF.value
//   costFormRef.value?.validate(async (valid: boolean) => {
//     if (valid) {
//       buttonLoading.value = true;
//       if (form.value.garageCostId) {
//         await updateCost(form.value).finally(() =>  buttonLoading.value = false);
//       } else {
//         await addCost(form.value).finally(() =>  buttonLoading.value = false);
//       }
//       proxy?.$modal.msgSuccess("修改成功");
//       dialog.visible = false;
//       await getList();
//       editFlag.value = false
//     }
//   });
// }

/** 删除按钮操作 */
const handleDelete = async (row?: CostVO) => {
  const _garageCostIds = row?.garageCostId || ids.value;
  await proxy?.$modal.confirm('是否确认删除数据项？').finally(() => loading.value = false);
  await delCost(_garageCostIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/cost/export', {
    ...queryParams.value
  }, `车位管理费_${formatDate(new Date().getTime())}.xlsx`)
}

const xmOptions = ref()
const xmqueryParams = ref<ProjectQuery>({
  pageNum: 1,
})
const loadingmore = ref(false)
const loadingnomore = ref(false)
const xmhandleVisibleChange = (visible: any) => {
  try {
    if (visible) {
      // 如果下拉框显示
      let CWDropdown: any = document.getElementsByClassName('CWDropdown')[0].parentElement.parentElement
      // 监听下拉框滚动事件
      CWDropdown.addEventListener('scroll', xmloadNextPage)
    } else {
      // 如果下拉框隐藏
      let CWDropdown: any = document.getElementsByClassName('CWDropdown')[0].parentElement.parentElement
      // 移除下拉框滚动事件监听
      CWDropdown.removeEventListener('scroll', xmloadNextPage)
    }
  } catch (error) {}
}

const xmloadNextPage = async () => {
  // let CWDropdown: any = document.querySelector('.el-select-dropdown__wrap');
  let CWDropdown: any = document.getElementsByClassName('CWDropdown')[0].parentElement.parentElement;
  // 判断下拉框是否触底
  if (CWDropdown.scrollTop + CWDropdown.clientHeight >= CWDropdown.scrollHeight - 2) {
    loadingnomore.value = false
    loadingmore.value = true
    if (xmOptions.value.length + 1 <= XQtotal.value && loadingmore.value) {
      xmqueryParams.value.pageNum ++
      const res = await listProject(xmqueryParams.value)
      xmOptions.value.length + 1 <= XQtotal.value?xmOptions.value.push(...res.rows):''
      loadingmore.value = false
    }else{
      loadingmore.value = false
      CWDropdown.removeEventListener('scroll', xmloadNextPage)
      loadingnomore.value = true
    }
  } else {
    loadingnomore.value = true
  }
}
const queryParamsSF = ref({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined,
  chargeCategory: undefined
});

const CWGLF = ref(0)

onMounted(async() => {
  if (window.history.state.back.includes('/costManagement/parkingLotCostAdd')) {
    // sessionStorage.removeItem("searchCKFlag")
    if (sessionStorage.getItem("searchCKFlag")=='0') {
      //如果有就读取缓存里面的数据
      queryParams.value = JSON.parse(sessionStorage.getItem("queryCKParams"))
    } else {
      sessionStorage.removeItem("queryCKParams")
    }
  } else {
    sessionStorage.removeItem("searchCKFlag")
    sessionStorage.removeItem("queryCKParams")
  }
  await getList();
  const xm = await listProject(xmqueryParams.value);
  xmOptions.value = xm.rows
  XQtotal.value = xm.total
  queryParamsSF.value.chargeCategory = charge_category.value[4].value
  const res = await listStandard(queryParamsSF.value);
  CWGLF.value = form.value.garageManagementCost = res.rows[0].chargeMoney
});
</script>
<style>
.parkingCostSearch .el-form--inline .el-form-item{
    align-items: center;
}
</style>